package com.itheima.aop;

import com.itheima.anno.Log;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class LogAop {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.itheima.anno.Log)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //获取操作人id
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer id = (Integer)claims.get("id");
        //获取操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //获取操作类名
        String className = pjp.getTarget().getClass().getName();
        //获取操作方法名
        String methodName = pjp.getSignature().getName();
        //获取操作方法参数
        Object[] args = pjp.getArgs();
        String methodParams = args.toString();
        //获取操作方法返回值
        long start = System.currentTimeMillis();
        Object proceed = pjp.proceed();
        long end = System.currentTimeMillis();
        long costTime = end - start;


        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(id);
        operateLog.setOperateTime(operateTime);
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(methodParams);
        String returnValue;
        operateLog.setCostTime(costTime);
        if(proceed==null){
            returnValue="null";
        }else {
            returnValue=proceed.toString();
        }
        operateLog.setReturnValue(returnValue);

        operateLogMapper.insert(operateLog);
        return proceed;

    }
}
